$.getUrlParam = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
};
//生成唯一编号
function newGuid()  
{  
    var guid = "";  
    for (var i = 1; i <= 32; i++){  
      var n = Math.floor(Math.random()*16.0).toString(16);  
      guid +=   n;  
      if((i==8)||(i==12)||(i==16)||(i==20))  
        guid += "-";  
    }  
    return guid;      
}
/*填空宽度控制*/
var textWidth = function(text){ 
    var sensor = $('<pre>'+ text +'</pre>').css({display: 'none'}); 
    $('body').append(sensor); 
    var width = sensor.width();
    sensor.remove();
    return width;
};
function changeText(obj){
    $(obj).width(textWidth($(obj).val())+30);
}

/* 创建编辑器  */
var E = window.wangEditor;
var editor = new E('#editor');


/*
 * 初始化
 ***/
$(function() {
	
	//初始化编辑器
	editor.customConfig.uploadImgMaxSize = 6 * 1024 * 1024;
	editor.customConfig.uploadImgMaxLength = 5;
	editor.customConfig.uploadFileName = 'myFileName';
	editor.customConfig.uploadImgHeaders = {
	       'Accept' : 'multipart/form-data'
	   };
	editor.customConfig.menus = [
		'image',
	    'emoticon'//加入空格
	];
	editor.customConfig.uploadImgServer = '/exam/files/upload';
	editor.customConfig.showLinkImg = false;
	editor.create();
	
    $(".selectpicker").selectpicker({  
        noneSelectedText : '选择科目'  
        });  
  
        $(window).on('load', function() {
        	$('.selectpicker').selectpicker('refresh');
        	$('.selectpicker').selectpicker('val', '');
        });
        // 下拉数据加载
    $.ajax({
        type : 'get',  
        url :"teacher/getSubjects",  
        dataType : 'json',  
        success : function(datas) {// 返回list数据并循环获取
            var select = $("#slpk");  
            for (var i = 0; i < datas.length; i++) {  
                select.append("<option value='"+datas[i].id+"'>"  
                        + datas[i].name + "</option>");  
            }
            $('.selectpicker').selectpicker('refresh');
            $('.selectpicker').selectpicker('val', '');
            
          //加载完选项再加载编辑信息
            var id = $.getUrlParam('id');
            if(id!=null&&id!=""){
            	//加载信息
            	$.ajax({
            		url:'blank/findOne',
            		type:'post',
            		dataType:'json',
            		data:{id:id},
            		success:function(data){
            			if(null!=data){
            				//加载题目信息
            				$('#id').val(data.id);
            				$('#num').val(data.num);
            				
            				if(data.subject!=null)
            					$('.selectpicker').selectpicker('val', data.subject.id);
            				editor.txt.html(data.title);
            				
            				var blankList = $('.the-blank');
            				for(var i=0;i<blankList.length;i++){
            					$(blankList[i]).val(data.blanks[i+1].content);
            					$(blankList[i]).data('option_id',data.blanks[i+1].id);
            					$(blankList[i]).data('option_num',data.blanks[i+1].num);
            				}
            				
            			}else{
            				window.location.href="/exam/tch_single";
            			}
            		},
            		error:function(){
            			Modal.alert({msg:'出错！'});
            			window.location.href="/exam/tch_single";
            		}
            	});
            }
        }  
    });
});
/* 单选题信息提交 */
$("#blankForm").submit(function(event){
	var blank = {};
	var blanks = {};
	
	var id = $('#id').val();
	var num = $('#num').val();
	$(blank).attr("id",id);
	$(blank).attr("num",num);

	var subject = {};
	var subjectId = $('#slpk option:selected').val();
	$(subject).attr("id",subjectId);
	$(blank).attr("subject",subject);
	
	var inputs = $('.the-blank');
	for(var i=0;i<inputs.length;i++){
		var option = {};
		
		var option_id = $(inputs[i]).data('option_id');
		var option_num = $(inputs[i]).data('option_num');
		$(option).attr("id",option_id);
		if(option_num==null||option_num=="")
			option_num = newGuid();
		$(option).attr("num",option_num);
		
		$(option).attr("content",inputs[i].value);
		$(blanks).attr((i+1),option);
	}
	$(blank).attr("blanks",blanks);
	
	var content = editor.txt.html();
	if(content==null||content==""||content=="<p><br></p>"){
		alert("题干不能为空！");
		return false;
	}
	$(blank).attr("title",content);
	
	var result = JSON.stringify(blank);
	console.log(result)
	
	$.ajax({
		url:'blank/saveOrUpdate',
		type:'post',
		dataType:'json',
		data:{blank:result},
		success:function(data){
			alert(data.msg);
			if(data.success)
				window.location.href="tch_blank_form";
		},
		error:function(){
			alert("出错！");
		}
	});
	
	return false;
});
function test(){
	var blank = {};
	var blanks = {};
	
	var id = $('#id').val();
	var num = $('#num').val();
	
	var inputs = $('.the-blank');
	for(var i=0;i<inputs.length;i++){
		$(blanks).attr((i+1),inputs[i].value);
	}
	console.log(JSON.stringify(blanks));
	
	
	
	var content = editor.txt.html();
	console.log(content);
	$("body").append(content);
	alert($('#slpk option:selected').val());
}